<template>
  <!-- 手机号登录 or 密码登录 -->
  <view :style="{ height: statusHeight + 'rpx' }"></view>
  <view class="custom_nav" :style="{ top: statusHeight + 20 + 'rpx' }">
    <uni-icons @click="goBack" type="left" color="#000" size="25"></uni-icons>
  </view>
  <view class="pages">
    <view class="login_info_box">
      <!-- <u-tabs
      :list="[{ name: '验证码登录' }, { name: '密码登录' }]"
      lineWidth="73rpx"
      lineColor="#333333"
      lineHeight="8rpx"
      :activeStyle="{
        color: '#333',
        fontSize: '32rpx',
        fontWeight: '800',
        transform: 'scale(1.05)',
      }"
      :inactiveStyle="{ color: '#666666', fontSize: '32rpx', transform: 'scale(1)' }"
      itemStyle=" height: 54px;padding-left:30rpx;padding-right:30rpx"
      @click="changeLoginType"
    ></u-tabs>
    <view class="tab_line"></view> -->

      <view class="verification_title">验证码登录</view>

      <swiper class="swiper" :current="current" disable-touch :duration="210">
        <swiper-item style="margin-left: 10rpx">
          <view class="input_c">
            <view class="hint">+86</view>
            <up-input
              fontSize="32rpx"
              shape="circle"
              type="number"
              v-model="account"
              placeholder="手机号"
              border="none"
              maxlength="11"
              placeholderStyle="font-size:28rpx;color:#999999;"
            />
          </view>
          <view class="input_c">
            <up-input
              fontSize="30rpx"
              shape="circle"
              type="number"
              v-model="code"
              class="w-633"
              placeholder="验证码"
              border="none"
              maxlength="6"
              placeholderStyle="font-size:28rpx;color:#999999;"
              @confirm="login"
            >
              <template #suffix>
                <u-code
                  :seconds="seconds"
                  :keepRunning="true"
                  @end="end"
                  @start="start"
                  ref="uCodeRef"
                  @change="codeChange"
                ></u-code>
                <u-button
                  :color="disabled ? '#D2D2D2' : '#00C1B9'"
                  :disabled="disabled"
                  class="send_code_btn flex-center co-33"
                  @tap="getCode"
                  >{{ tips }}</u-button
                >
              </template>
            </up-input>
          </view>
        </swiper-item>
        <!-- <swiper-item>
          <view class="input_c">
            <up-input
              fontSize="32rpx"
              shape="circle"
              type="number"
              v-model="account"
              placeholder="手机号"
              border="none"
              maxlength="11"
              placeholderStyle="font-size:28rpx;color:#999999;"
            />
          </view>
          <view class="input_c">
            <up-input
              fontSize="32rpx"
              shape="circle"
              v-model="password"
              class="w-633"
              placeholder="密码"
              border="none"
              maxlength="16"
              :type="passwordType"
              placeholderStyle="font-size:28rpx;color:#999999;"
              @confirm="login"
            >
              <template #suffix>
                <image
                  v-if="!suffixIcon"
                  src="@/static/my/password_icons.png"
                  class="password_icon"
                  @click="showPassword"
                />
                <image
                  v-else
                  src="@/static/my/password_icon.png"
                  class="password_icon"
                  @click="showPassword"
                />
              </template>
            </up-input>
          </view>
        </swiper-item> -->
      </swiper>

      <view class="register_h" v-if="current == 1">
        <view class="text"> 还没有账号？ </view>
        <view class="text-1" @click="navigateTo(`/pages-users/login-page/register`, 0)">
          立即注册
        </view>
      </view>

      <up-button class="login" :class="{ login_active: isDisabled }" @click="login">登录</up-button>

      <view class="login-type" :class="{ active_center: current == 1 }">
        <view
          class="text-2 animate__animated"
          style="margin-top: 20rpx; font-size: 28rpx; color: #5c5c5c"
          @click="showLoginByOauth"
        >
          切换到一键登录
        </view>
        <view
          v-if="current == 1"
          class="text-3"
          @click="navigateTo('/pages-users/login-page/retrieve', 0)"
        >
          忘记密码
        </view>
      </view>
    </view>
    <view class="agreement">
      <view class="round_c" @click="isChecked = !isChecked">
        <view class="round" :class="{ round_active: isChecked }">
          <u-icon name="checkmark" size="10" :bold="true" v-if="isChecked" color="#FFF"></u-icon>
        </view>
      </view>

      <view class="agreement_right">
        我已阅读并同意
        <text @click="navigateTo(`/pages-users/common-agreement/index?type=0`)">
          《咪婴伴侣医生端用户协议》
        </text>
        和
        <text @click="navigateTo(`/pages-users/common-agreement/index?type=2`)">
          《咪婴伴侣医生端隐私协议》
        </text>
        并使用本机号码登录
      </view>
    </view>
  </view>
  <h-login ref="loginRef"></h-login>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow, onLoad, onReady } from '@dcloudio/uni-app'
import { showToast, navigateTo, showLoading, hideLoading, switchTab, checkPhone } from '@/utils'
import { loginByPasswordApi, loginBySmsApi, sendSmsApi } from '@/services/my/login'
import { getUserInfo } from '@/pages/my/utils'
import { useMemberStore } from '@/stores'
import { getIMApi } from '@/services/my/login'
import { navigateBack } from '@/libs/uniApi'

const loginRef = ref<any>(null)
const isChecked = ref(false)
const suffixIcon = ref<boolean>(false) // 密码框icon
const passwordType = ref<string>('password') // 密码框类型 默认为password
const tips = ref<any>('') // 验证码提示
const seconds = ref<number>(60) // 倒计时秒数
const uCodeRef = ref<any>(null) /// 验证码组件实例
const current = ref<number>(0) // 当前索引

const account = ref<string>('') // 账号
const password = ref<string>('') // 密码
const code = ref<string>('') // 验证码
const os = ref()

var registrationID = ref('')
/**
 * 使用computed 计算按钮颜色
 */
const isDisabled = computed(() => {
  let flag = false
  if (current.value == 0) {
    if (checkPhone(account.value) && code.value.length === 4 && isChecked.value) {
      flag = true
    } else {
      flag = false
    }
  } else if (current.value == 1) {
    if (
      checkPhone(account.value) &&
      password.value.length >= 6 &&
      password.value.length <= 16 &&
      isChecked.value
    ) {
      flag = true
    } else {
      flag = false
    }
  }
  return flag
})
const ll = ref()
const statusHeight = ref()
onLoad((o) => {
  uni.getSystemInfo({
    success: (e) => {
      statusHeight.value = e?.statusBarHeight * 2
    },
  })
  ll.value = o?.ll
  uni.getSystemInfo({
    success: (e) => {
      os.value = e.osName
      console.log(e)
    },
  })
})
onReady(() => {
  // #ifdef APP-PLUS || APP-IOS || APP-ANDROID
  uni.preLogin({
    provider: 'univerify',
  })
  // #endif
})
function showLoginByOauth() {
  loginRef.value.open(false)
}
const lastPage = ref(null)

function goBack() {
  loginRef.value.open()
  const store = useMemberStore()
  store.setclose(1)
}
onShow(() => {
  let pages = getCurrentPages() // 获取当前页面栈
  if (pages.length > 1) {
    let prevPage = pages[pages.length - 2] // 上一页为栈顶第二个元素
    lastPage.value = prevPage.route // 输出上一页对象
    console.log(pages)
  }
  // #ifdef APP
  uni.getPushClientId({
    success: (res) => {
      uni.setStorageSync('registerID', res.cid)
      registrationID.value = res.cid
      console.log(registrationID.value)
    },
    fail(err) {
      console.log(err)
    },
  })
  // #endif
})

/**
 * 登录
 */
async function login() {
  const userStore = useMemberStore()

  // if (!isDisabled.value) return
  try {
    showLoading('正在登录')
    userStore.clearToken()
    userStore.clearUserInfo()
    let res: any = {}
    if (current.value === 1) {
      if (!account.value) return showToast('请输入手机号码')
      if (!password.value) return showToast('请输入密码')
      if (!isChecked.value) {
        showToast('请先勾选协议', 'none', false, 3000)
        return
      }
      if (!/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[a-z])\S*$/.test(password.value))
        return showToast('请输入正确密码', 'none', false, 3000)
      // 密码登录
      res = await loginByPasswordApi({
        APPID: '__UNI__EEA0169',
        account: account.value,
        password: password.value,
        registration_id: registrationID.value,
        nickname: userStore?.casualUser?.nickname,
        avatar: userStore?.casualUser?.avatar,
        is_download_app: 1,
        source: os.value == 'IOS' ? 2 : 1,
        identity_type: userStore.casualUser?.identity_type || 0,
        identity_status: userStore.casualUser?.identity_status,
      })
    } else {
      // 验证码登录
      console.log(213213)
      if (!account.value) return showToast('请输入手机号码')
      if (!code.value) return showToast('请输入验证码')
      if (!isChecked.value) {
        showToast('请先勾选协议', 'none', false, 3000)
        return
      }
      res = await loginBySmsApi({
        mobile: account.value,
        code: code.value,
        registration_id: registrationID.value,
        type: 1,
      })
    }
    console.log(res)
    if (res.message === '登录成功') {
      userStore.setToken(res.data.token)
      console.log(res.data.token, '8888888888888888888888888888888')
      setTimeout(() => {
        userStore.setclose(1)
      }, 300)
      getIMApi({ doctor_im_id: res?.data?.im?.doctor_im_id }).then((res: any) => {
        userStore.setIM(res.data)
      })
      await getUserInfo()
      switchTab('/pages/index/index')
    }
    showToast(res.message)
    hideLoading()
  } catch (error) {
    hideLoading()
  }
}

/**
 * 密码框显示隐藏
 */
function showPassword() {
  suffixIcon.value = !suffixIcon.value
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password'
}

/**
 * 验证码倒计时结束
 */
function codeChange(text: string) {
  tips.value = text
}
const disabled = ref(false)
/**
 * 获取验证码
 */
async function getCode() {
  if (!checkPhone(account.value)) {
    showToast(account.value.length ? '请输入正确的手机号码' : '请输入手机号码')
    return
  }
  if (uCodeRef.value.canGetCode) {
    showLoading('正在获取验证码')
    const res: any = await sendSmsApi({ phone: account.value })
    console.log(res)
    hideLoading()
    if (res.message === '发送成功，有效期60s') {
      showToast('验证码已发送')
      uCodeRef.value.start()
      disabled.value = true
    } else {
      showToast(res.message)
    }
  } else {
    showToast('倒计时结束后再发送')
    disabled.value = true
  }
}

/**
 * 倒计时结束
 */
function end() {
  disabled.value = false
}

/**
 * 倒计时开始
 */
function start() {}

/**
 * 切换登录方式
 */
function changeLoginType(e: any) {
  current.value = e.index
}
</script>
<style>
page {
  position: relative;
}
</style>
<style scoped lang="scss">
.custom_nav {
  padding: 0 24rpx 30rpx 0rpx;
  position: fixed;
  left: 24rpx;
}
.pages {
  width: 750rpx;
  min-height: 90vh;
  // padding: 174rpx 50rpx 30rpx 50rpx;
  .login_info_box {
    width: 94%;
    // margin: 0rpx 0rpx 180rpx 0rpx;
    position: fixed;
    left: 40rpx;
    top: 280rpx;
  }
  .verification_title {
    font-size: 40rpx;
    color: #202020;
    margin-left: 10rpx;
  }
  .tab_line {
    width: 100%;
    height: 1rpx;
    background-color: #ededed;
  }

  .swiper {
    height: 200rpx;
    margin-top: 50rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .input_c {
    display: flex;
    align-items: center;
    width: 650rpx;
    height: 88rpx;
    border-radius: 86rpx;
    background-color: #f4f4f4;
    padding: 0 26rpx;
    margin-bottom: 30rpx;

    .password_icon {
      width: 46rpx;
      height: 40rpx;
    }

    .hint {
      font-weight: 500;
      font-size: 32rpx;
      color: #333333;
      margin-right: 28rpx;
    }
    .send_code_btn {
      width: 190rpx;
      height: 68rpx;
      border-radius: 48rpx;
      margin-left: 116rpx;
      margin-bottom: 4rpx;
    }
  }

  .register_h {
    width: 100%;
    height: 30rpx;
    display: flex;

    margin-top: 31rpx;
    padding: 0 18rpx;

    .text {
      font-size: 26rpx;
      font-weight: 500;
      color: #999999;
      margin-right: 10rpx;
    }

    .text-1 {
      font-size: 26rpx;
      font-weight: 500;
      color: #0074fc;
    }
  }

  .agreement {
    position: absolute;
    bottom: 150rpx;
    left: 50rpx;
    // width: 100%;
    display: flex;
    // align-items: center;

    .round_c {
      padding-top: 6rpx;
      width: 34rpx;
      height: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;

      .round_active {
        border: none !important;
        background-color: #00c1b9 !important;
      }

      .round {
        width: 26rpx;
        height: 26rpx;
        border-radius: 50%;
        opacity: 1;
        border: 1rpx solid #999999;
        display: flex;
        align-items: center;
        justify-content: center;
        // margin-right: 8rpx;
      }
    }

    .agreement_right {
      width: 614rpx;
      font-weight: 500;
      font-size: 26rpx;
      line-height: 1.5;
      color: #5c5c5c;

      text {
        color: #00c1b9;
        line-height: 1;
      }
    }
  }

  .w-633 {
    width: 633rpx;
  }

  .type-or-pass {
    display: flex;
    flex-wrap: nowrap;
    overflow: hidden;
  }

  .login {
    width: 650rpx;
    height: 88rpx;
    background: #d6e2e1;
    border-radius: 59rpx 59rpx 59rpx 59rpx;
    opacity: 1;
    line-height: 80rpx;
    text-align: center;
    font-size: 32rpx;
    font-weight: 500;
    color: #ffffff;
    margin-top: 50rpx;
  }

  .login_active {
    background: #00c1b9 !important;
  }

  .active_center {
    justify-content: space-between !important;
  }

  .login-type {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30rpx;

    .text-2 {
      background-color: transparent;
      font-weight: 500;
      font-size: 26rpx;
      color: #333333;
    }

    .text-3 {
      font-size: 26rpx;
      font-weight: 500;
      color: #999999;
    }
  }
}
::v-deep .u-input__content__field-wrapper {
  width: 300rpx !important;
}

::v-deep .u-input__content__field-wrapper__field {
  height: 86rpx;
  width: 300rpx !important;
}
::v-deep .uni-input-wrapper {
  width: 300rpx !important;
}

::v-deep .u-button {
  height: 48rpx;
  // padding: 0 11rpx !important;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
  line-height: 48rpx;
  text-align: center;
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 24rpx;
  color: rgba(246, 246, 246, 0.96);
  margin-left: 10rpx;
}
// ::v-deep .u-button {
//   width: 220rpx;
//   text-align: right;
// }
</style>
